import {
  AlipayCircleOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import {
  FormattedMessage,
  Helmet,
  SelectLang,
  useIntl,
  useModel,
} from '@umijs/max';
import { Alert, App, Tabs } from 'antd';
import { createStyles } from 'antd-style';
import React, { useState } from 'react';
import { flushSync } from 'react-dom';
import { Footer } from '@/components';
import { login } from '@/services/ant-design-pro/api';
import { getFakeCaptcha } from '@/services/ant-design-pro/login';
import Settings from '../../../../config/defaultSettings';

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(249, 243, 243, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage: "url('/bgc.3dc3b233.png')", // 背景图片路径
      backgroundSize: '100% 100%',
    },
    customTabs: {
      '& .ant-tabs-nav': {
        width: '100%',
        marginBottom: '32px',
      },
      '& .ant-tabs-nav-wrap': {
        display: 'flex',
        justifyContent: 'center',
      },
      '& .ant-tabs-nav-list': {
        width: '100%',
        display: 'flex',
        gap: '0',
      },
      '& .ant-tabs-tab + .ant-tabs-tab': {
        marginLeft: '0 !important', // 关键：清除相邻标签的左间距
      },
      '& .ant-tabs-tab': {
        flex: 1,
        display: 'flex',
        justifyContent: 'center',
        padding: '12px 0',
        fontSize: '16px',
        fontWeight: '500',
        margin: 0, // 关键：移除默认margin
        border: '1px solid #d9d9d9',
        transition: 'all 0.3s',
      },
    },
  };
});

const ActionIcons = () => {
  const { styles } = useStyles();

  return (
    <>
      <AlipayCircleOutlined
        key="AlipayCircleOutlined"
        className={styles.action}
      />
      <TaobaoCircleOutlined
        key="TaobaoCircleOutlined"
        className={styles.action}
      />
      <WeiboCircleOutlined
        key="WeiboCircleOutlined"
        className={styles.action}
      />
    </>
  );
};

const Lang = () => {
  const { styles } = useStyles();

  return (
    <div className={styles.lang} data-lang>
      {SelectLang && <SelectLang />}
    </div>
  );
};

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>();
  const [type, setType] = useState<string>('admin');
  const { initialState, setInitialState } = useModel('@@initialState');
  const { styles } = useStyles();
  const { message } = App.useApp();
  const intl = useIntl();

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };
  const handleSubmit = async (values: API.LoginParams) => {
    try {
      const loginValues = {
        ...values,
        type: type
      };
      // 类型断言匹配后端实际返回结构
      const msg = (await login(loginValues)) as API.LoginResult & {
        code: number;
        msg: string; // 后端用 msg 字段返回提示信息
        info: { id: string }; // 用户信息
        list: any[]; // 菜单列表
        url: string; // admin 相关地址
      };

      if (msg.code === 1) {
        // 登录成功：优先使用后端返回的 msg
        message.success(msg.msg || intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        }));
        // 存储后端返回的数据（匹配 JSON 中的 list 字段）
        localStorage.setItem('userinfo', JSON.stringify(msg.info));
        localStorage.setItem('camenu', JSON.stringify(msg.list)); // 后端返回了 list 数组
        localStorage.setItem('uid', msg.info.id);
        localStorage.setItem('admin', msg.url);
        sessionStorage.setItem('loginPassword', values.password);
        sessionStorage.setItem('voucher', 'Login-credentials');// 登录成功后，设置一个标识
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        const redirectUrl = urlParams.get('redirect') || '/';
        setTimeout(() => {
          window.location.href = redirectUrl;
        }, 500);
        return;
      } else {
        // 登录失败：使用后端返回的 msg
        setUserLoginState(msg);
        const loginFailureMessage = msg.msg || intl.formatMessage({
          id: 'pages.login.failure',
          defaultMessage: '登录失败，请重试！',
        });
        message.error(loginFailureMessage);
      }
    } catch (error) {
      // 网络错误/异常：使用默认提示
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
  };
  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {intl.formatMessage({
            id: 'menu.login',
            defaultMessage: '登录页',
          })}
          {Settings.title && ` - ${Settings.title}`}
        </title>
      </Helmet>
      <div
        style={{
          flex: '1',
          padding: '75px 0 32px 0',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
        }}
      >
        <span style={{
          textAlign: 'center',
          fontSize: '32px',
          fontWeight: 600,
          color: '#f7f8f9ff',
          width: '100%',
          maxWidth: '75vw',
          textShadow: '0 2px 8px rgba(0, 0, 0, 0.8)',
          display: 'block',
        }}>
          运营管理公司人力资源管理系统
        </span>

        {/* 表单 */}
        <LoginForm
          contentStyle={{
            minWidth: 500,
            maxWidth: '75vw',
            minHeight: '350px',
            backgroundColor: '#ffffff',
            borderRadius: '15px',
            padding: '55px 60px',
            boxShadow: '0 4px 20px rgba(0, 0, 0, 0.08)',
          }}
          title={null}
          initialValues={{ autoLogin: true }}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
          submitter={{
            searchConfig: {
              submitText: '登录',
            },
            render: (_, dom) => {
              return (
                <div style={{ textAlign: 'center', width: '100%' }}>
                  <button
                    type="submit"
                    style={{
                      width: '100%',
                      height: '45px',
                      backgroundColor: '#1890ff',
                      color: '#fff',
                      border: 'none',
                      borderRadius: '8px',
                      fontSize: '16px',
                      fontWeight: '500',
                      cursor: 'pointer',
                      transition: 'background-color 0.3s',
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.backgroundColor = '#40a9ff';
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.backgroundColor = '#1890ff';
                    }}
                  >
                    登录
                  </button>
                </div>
              );
            },
          }}
        >
          <div className={styles.customTabs}>
            <Tabs
              activeKey={type}
              onChange={setType}
              centered
              items={[
                {
                  key: 'admin',
                  label: '管理员登录',
                },
                {
                  key: 'employee',
                  label: '员工登录',
                },
              ]}
            />
          </div>

          {/* 账号输入框：必填校验 + 样式调整 */}
          <>
            <ProFormText
              name="account"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined />,
              }}
              placeholder='账号'
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.login.account.required"
                      defaultMessage="请输入用户名!"
                    />
                  ),
                },
                {
                  min: 5,
                  message: (
                    <FormattedMessage
                      id="pages.login.account.minLength"
                      defaultMessage="用户名至少5个字符!"
                    />
                  ),
                },
                {
                  max: 11,
                  message: (
                    <FormattedMessage
                      id="pages.login.account.maxLength"
                      defaultMessage="用户名最多11个字符!"
                    />
                  ),
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined />,
              }}
              placeholder="密码"
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.login.password.required"
                      defaultMessage="请输入密码！"
                    />
                  ),
                },
                {
                  min: 6,
                  message: (
                    <FormattedMessage
                      id="pages.login.password.minLength"
                      defaultMessage="密码至少6个字符!"
                    />
                  ),
                },
                {
                  max: 18,
                  message: (
                    <FormattedMessage
                      id="pages.login.password.maxLength"
                      defaultMessage="密码最多18个字符!"
                    />
                  ),
                },
              ]}
            />
          </>
        </LoginForm>
      </div>
    </div>
  );
};

export default Login;